#include "log.hpp"
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>

using namespace std;

Log lg;

void Usage(const std::string &proc)
{
    cout << "\n\tUsage: " << proc << " serverip serverport\n"
         << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    socklen_t len = sizeof(server);
    while (true)
    {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            lg(Fatal, "socket error");
            exit(2);
        }

        int cnt = 5;              // 重连尝试次数
        bool isreconnect = false; // 是否重连
        do
        {
            // 发起连接
            int n = connect(sockfd, (struct sockaddr *)&server, len);
            if (n < 0)
            {
                isreconnect = true;
                lg(Warning, "Service exception, reconnecting... %d", cnt);
                cnt--;
                sleep(2);
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            lg(Fatal, "user offine...");
            break;
        }

        // while (true)
        //{
        std::string message;
        cout << "Please Enter#";
        getline(cin, message);
        int n = write(sockfd, message.c_str(), sizeof(message));
        if (n < 0)
        {
            isreconnect = true;
            lg(Warning, "client write error...");
            // continue;
        }
        char inbuffer[1024];
        int n1 = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
        if (n1 > 0)
        {
            inbuffer[n1] = 0;
            cout << inbuffer << endl;
        }

        //}
        close(sockfd);
    }

    return 0;
}